package com.example.JavaWebApi.core.apiinterceptors;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @PROJECT_NAME: JavaWebApi
 * @DESCRIPTION: 拦截器配置
 * @Author: YangZe
 * @DATE: 2021/11/28 16:25
 */
//下面被注释的这个注解会导致静态文件访问不到
//@EnableWebMvc
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Autowired
    private JwtInterceptor jwtInterceptor;
    @Value("${spring.web.uploadpath}")
    private String targetFilePath;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor);
        //registry.addInterceptor(new LogInterceptor());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/documents/**")
                .addResourceLocations("classpath:/templates/documents/");
        registry.addResourceHandler("/batchFile/**")
                //.addResourceLocations("classpath:/templates/batchfiles/")
                .addResourceLocations("file:" + (targetFilePath.endsWith("/") ? targetFilePath : targetFilePath + "/"))
                .setCacheControl(CacheControl.noCache())
                .setCachePeriod(0);
//        registry.addResourceHandler("/test/**").addResourceLocations("C:\\Users\\tengfei8771\\Desktop\\excel\\");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  //配置了所有的路由都可以跨域请求
                .allowedHeaders("*")  //配置了允许发送的自定义请求头
                .allowedMethods("*")  //配置了路径下所有的请求都可以跨域请求
                .allowedOriginPatterns("*")  //解决跨域资源共享（CORS）问题的一个配置项，用于允许来自任何来源的跨域请求
                .allowCredentials(true)  //指定在跨域请求中是否允许浏览器发送包含凭证信息的请求
                .maxAge(3600);  //指定在给定的时间范围内，是否允许浏览器缓存特定资源的请求结果。
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //将我们定义的时间格式转换器添加到转换器列表中,
        //这样jackson格式化时候但凡遇到Date类型就会转换成我们定义的格式
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.DEFAULT);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        objectMapper.registerModule(javaTimeModule);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        messageConverter.setObjectMapper(objectMapper);
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(0, messageConverter);
    }

}
